package com.kaaction.modules.market.api;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.kaaction.common.web.BaseController;
import com.kaaction.modules.market.entity.Event;
import com.kaaction.modules.market.entity.EventLottery;
import com.kaaction.modules.market.entity.EventLotteryDetail;
import com.kaaction.modules.market.entity.EventLotteryDrawHistory;
import com.kaaction.modules.market.service.EventLotteryDetailService;
import com.kaaction.modules.market.service.EventLotteryDrawHistoryService;
import com.kaaction.modules.market.service.EventLotteryService;
import com.kaaction.modules.market.service.EventService;

@Controller
@RequestMapping(value = "/api/v1/lottery")
public class LotteryApiController extends BaseController {
	
	@Autowired
	private EventService eventService;
	
	@Autowired
	private EventLotteryService eventLotteryService;
	
	@Autowired
	EventLotteryDetailService eventLotteryDetailService;
	
	@Autowired
	EventLotteryDrawHistoryService eventLotteryDrawHistoryService;

	/**
	 * 抽奖
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = {"draw"})
	public void draw(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String eventId = request.getParameter("eventId");
		String channelId = request.getParameter("channelId");
		String openid = request.getParameter("openid");
	
		response.setHeader("Access-Control-Allow-Origin", "*");
		
		logger.info("处理抽奖逻辑:eventId="+eventId+",channelId="+channelId+",openid="+openid);
		Event event = eventService.get(eventId);
		Map result = new HashMap();
		//1.记录抽奖事件
		EventLotteryDrawHistory eventLotteryDrawHistory = eventLotteryDrawHistoryService.getByEventId(eventId,openid);
		if(eventLotteryDrawHistory != null){
			int customerDrawCount = eventLotteryDrawHistory.getCustomerDrawCount();
			logger.info("此人有抽奖的记录，已经抽过"+customerDrawCount+"次了");
			
			if(event != null && event.getEnrollLimit() != null & event.getEnrollLimit().intValue() >0){
				if(eventLotteryDrawHistory.getCustomerDrawCount() >= event.getEnrollLimit()){
					//超过抽奖次数了
					result.put("result",-5);
				} else {
					result = lotteryLogic(eventId,openid,eventLotteryDrawHistory);
				}
			}
		} else {
			result = lotteryLogic(eventId,openid,null);
		}
		
		PrintWriter pw = response.getWriter();
		String jsonResult = JSON.toJSONString(result);
		logger.info("jsonResult = " + jsonResult);
		pw.write(jsonResult);
		pw.flush();
		pw.close();
	}
	
	private Map lotteryLogic(String eventId,String openId,EventLotteryDrawHistory eventLotteryDrawHistory){
		int customerDrawCount = 0;
		Map result = new HashMap();
		List<EventLottery> list = eventLotteryService.findByEventId(eventId);
		if(list != null && list.size() >= 4){
			int rank =  eventLotteryService.draw(list);
			logger.info("中了奖次为:"+rank);
			if(rank < 5 && rank > 0) {
				EventLottery winPrize = list.get(rank - 1);
				
				String token = UUID.randomUUID().toString();
				EventLotteryDetail eventLotteryDetail = new EventLotteryDetail();
				eventLotteryDetail.setEventId(eventId);
				eventLotteryDetail.setEventLottery(winPrize.getId());
				eventLotteryDetail.setWinnerDate(new Date());
				eventLotteryDetail.setRemarks(token);
				eventLotteryDetail.setWinnerName(winPrize.getName());
				eventLotteryDetailService.save(eventLotteryDetail);
				logger.info("新增一条中奖记录:"+eventLotteryDetail.getId());
				
				result.put("result", convertPrizeToLoc(rank));
				result.put("name", winPrize.getName());
				result.put("url", "http://www.xxx.com");
				result.put("tk", token);
			} else {
				result.put("result", randLoc());
			}
		}
		
		if(eventLotteryDrawHistory == null){
			eventLotteryDrawHistory = new EventLotteryDrawHistory();
			eventLotteryDrawHistory.setCustomerDrawCount(0);
		}
		customerDrawCount = eventLotteryDrawHistory.getCustomerDrawCount();
			
		eventLotteryDrawHistory.setCustomerDrawCount(++customerDrawCount);
		eventLotteryDrawHistory.setEvent(eventId);
		eventLotteryDrawHistory.setCustomerAddress(openId);
		eventLotteryDrawHistoryService.save(eventLotteryDrawHistory);
		//
		return result;
	}
	
	//将奖品等级，转化为页面中的位置
	private int convertPrizeToLoc(int prizeRank){
		int result = 6;
		switch(prizeRank){
			case 1: result = 1;break;
			case 2: result = 3;break;
			case 3: result = 4;break;
			default:result = 6;
		}
		return result;
	}
	//将未中奖转化为页面中的位置
	private int randLoc(){
		int result = (int)(Math.random() * 4);
		switch(result){
			case 1: result = 2;break;
			case 2: result = 5;break;
			case 3: result = 7;break;
			default:result = 0;
		}
		return result;
	}
	
	/**
	 * 领奖
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = {"accept"})
	public void accept(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String eventId = request.getParameter("eventId");
		String channelId = request.getParameter("channelId");
		String token = request.getParameter("token");
		String dn = request.getParameter("dn");
		
		Map result = new HashMap();
		result.put("accept_result", "0");
		
		EventLotteryDetail eventLotteryDetail = eventLotteryDetailService.getByIdAndToken(eventId, token);
		if(eventLotteryDetail != null){
			//将放到service的一个事务中
			eventLotteryDetail.setDelFlag("0");
			eventLotteryDetail.setWinnerMobile(dn);
			eventLotteryDetailService.save(eventLotteryDetail);
			logger.info("保存中奖人电话:"+dn);
			
			logger.info("eventId:"+eventLotteryDetail.getEventId());
			EventLottery eventLottery = eventLotteryService.get(eventLotteryDetail.getEventId());
			if(eventLottery != null) {
				String quantityLeft = eventLottery.getQuantityLeft();
				logger.info("找到该奖品:.奖品数量还剩"+quantityLeft);
				if(StringUtils.isBlank(quantityLeft)){
					int quantityLeftInt = Integer.parseInt(quantityLeft);
					if(quantityLeftInt > 0){
						eventLottery.setQuantityLeft(String.valueOf(--quantityLeftInt));
						eventLotteryService.save(eventLottery);
						logger.info("奖品数量减1,变成"+quantityLeftInt);
						
						result.put("accept_result", "1");
						result.put("name", "myname");
						result.put("url", "http://www.xxx.com");
						result.put("tk", "yyyy");

					}
				}
			}
		}
		
		
		response.setHeader("Access-Control-Allow-Origin", "*");
		PrintWriter pw = response.getWriter();
		pw.write(JSON.toJSONString(result));
		pw.flush();
		pw.close();
	}
		
}
